//
//  UIImage+Category.m
//  VICategory
//
//  Created by MN on 2022/6/28.
//

#import "UIImage+Category.h"
#import "NSString+Category.h"
#import <objc/runtime.h>
@implementation UIImage (Category)

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method imageNamed = class_getClassMethod(self,@selector(imageNamed:));
        Method looha_ImageNamed = class_getClassMethod(self,@selector(looha_none_imageNamed:));
        method_exchangeImplementations(imageNamed, looha_ImageNamed);
    });
}
+ (instancetype)looha_none_imageNamed:(NSString*)name{
 
    if (![NSString isEmptyStr:name])  return  [self looha_none_imageNamed:name];
    else return nil;
}


/// 画虚线
/// @param imageSize imageSize
/// @param color color
+ (UIImage *)vi_drawLine:(CGSize)imageSize color:(UIColor *)color{
    UIGraphicsBeginImageContext(imageSize);
    UIImage *image = [UIImage new];
    [image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGFloat lengths[] = {5,2};
    CGContextRef line = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(line, color.CGColor);
    CGContextSetLineDash(line, 0, lengths, imageSize.height);
    CGContextMoveToPoint(line, 0, imageSize.height);
    CGContextAddLineToPoint(line, imageSize.width, imageSize.height);
    CGContextStrokePath(line);
    return UIGraphicsGetImageFromCurrentImageContext();
}

/// 获取bundle的图片
/// @param imageName 图片的名字
/// @param bundleName bundle的名字
/// @param targetClass bundle所在模块的任一类名
+ (instancetype)vi_imageWithName:(NSString *)imageName
                      bundleName:(NSString *)bundleName
                     targetClass:(Class)targetClass{
    NSInteger scale = [[UIScreen mainScreen] scale];
    NSBundle *currentBundle = [NSBundle bundleForClass:targetClass];
    NSString *name = [NSString stringWithFormat:@"%@@%zdx",imageName,scale];
    NSString *dir = [NSString stringWithFormat:@"%@.bundle",bundleName];
    NSString *path = [currentBundle pathForResource:name ofType:@"png" inDirectory:dir];
    return path ? [UIImage imageWithContentsOfFile:path] : nil;
}

///对图片尺寸进行压缩
- (UIImage *)vi_compressedImage;{
    UIGraphicsBeginImageContext(self.size);
    [self drawInRect:CGRectMake(0,0,self.size.width,self.size.height)];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return [self compressImageQuality:newImage toByte:1048576];
}
- (UIImage *)vi_compressedImageToMaxByte:(NSInteger)maxLength {
    
    NSData *data = UIImageJPEGRepresentation(self, 1);
    
    CGFloat compression = maxLength/data.length*1.0;
    if (compression>=1.0) return self;
    
    data = UIImageJPEGRepresentation(self, compression);
    UIImage *resultImage = [UIImage imageWithData:data];
    return resultImage;
   
}
/// 压缩图片文件
/// @param image image
/// @param maxLength  1M (1048576 字节)
- (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    return resultImage;
}

//给图片添加文字水印 默认左上角日期水印，右下角门店水印
- (UIImage *)vi_addWaterWithTimeText:(NSString *)timeText
                        storeName:(NSString *)storeName{
    NSString *store = storeName.length <= 15 ? storeName : [storeName substringToIndex:15];

    CGFloat texWith = [store vi_widthWithFontSize:50];
    
    return [self vi_addWaterWithTimeText:timeText
                               timePoint:CGPointMake(50, 50)
                               storeName:storeName
                               storePoint:CGPointMake(self.size.width-texWith-100,self.size.height-150)];
}
// 给图片添加文字水印
- (UIImage *)vi_addWaterWithTimeText:(NSString *)timeText
                           timePoint:(CGPoint)timePoint
                           storeName:(NSString *)storeName
                          storePoint:(CGPoint)storePoint{
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:50],
    NSForegroundColorAttributeName : [UIColor whiteColor],};
    
    //1.开启上下文
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0);
    //2.绘制图片
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    //添加时间文字水印
    [timeText drawAtPoint:timePoint withAttributes:attribute];
    //添加节点水印
    [storeName drawAtPoint:storePoint withAttributes:attribute];
    
    //3.从上下文中获取新图片
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    //4.关闭图形上下文
    UIGraphicsEndImageContext();
    //返回图片
    return newImage;
}

/// image切圆角
- (UIImage *)vi_radius:(CGFloat)radius size:(CGSize)size{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
    CGContextAddPath(contextRef,path.CGPath);
    CGContextClip(contextRef);
    [self drawInRect:rect];
    CGContextDrawPath(contextRef, kCGPathFillStroke);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

/// 图片缩放
- (UIImage *)imageCompressScale:(CGFloat)scale {
    UIGraphicsBeginImageContext(CGSizeMake(self.size.width * scale, self.size.height * scale));
    [self drawInRect:CGRectMake(0, 0, self.size.width * scale, self.size.height * scale)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

/**
 *  从图片中按指定的位置大小截取图片的一部分
 *
 *  @param image UIImage image 原始的图片
 *  @param rect  CGRect rect 要截取的区域
 *
 *  @return UIImage
 */
- (UIImage *)vi_imageFromImage:(UIImage *)image inRect:(CGRect)rect{
    
    //把像 素rect 转化为 点rect（如无转化则按原图像素取部分图片）
    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat x= rect.origin.x*scale,y=rect.origin.y*scale,w=rect.size.width*scale,h=rect.size.height*scale;
    CGRect dianRect = CGRectMake(x, y, w, h);

    //截取部分图片并生成新图片
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, dianRect);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
    return newImage;
}
@end
